package Server;

import Clients.Client;
import Clients.ClientList;
import java.net.*;
import java.io.*;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author Cliff
 */
public class Server {
    private int port;
    private ServerSocket serverSocket;
    private ClientList clientList;
    boolean stopFlag = false;
    private int maxClients;
    //Other variables
    private int memberCount = 0;
    /**
     * 
     * @param port 
     */
    public Server(int port){
        this.port = port;
        this.clientList = new ClientList();
    }
    
    /**
     * 
     * @param port
     * @param maxClients 
     */
    public Server(int port, int maxClients){
        this.port = port;
        this.maxClients = maxClients;
        this.clientList = new ClientList();
    }
    
    /**
     * 
     * @throws IOException 
     */
    public void init() throws IOException{
        serverSocket = new ServerSocket(port);
    }
    
    /**
     * 
     */
    public void start() throws IOException{
        while(!stopFlag){
            updateMemberList();
            handleMessages();
        }
    }
    
    /**
     * 
     */
    public void stop() throws IOException{
        clientList.removeAllClients();
        memberCount = 0;
        serverSocket.close();
    }
    
    /**
     * 
     */
    private void updateMemberList() throws IOException{
        Socket clientSocket = this.serverSocket.accept();
        
        PrintWriter out = new PrintWriter(
                clientSocket.getOutputStream(), true);
        BufferedReader in = new BufferedReader(
                new InputStreamReader(
                        clientSocket.getInputStream()));
        
        int id = memberCount;
        
        clientList.addClient(new Client(clientSocket,in,out,id));
    }
    
    /**
     * 
     */
    private void handleMessages(){
        
    }
}
